package com.tywj.buscustomerapp.view.activity;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.amap.api.services.core.PoiItem;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.bumptech.glide.Glide;
import com.tywj.buscustomerapp.R;
import com.tywj.buscustomerapp.utils.SPUtils;
import com.tywj.buscustomerapp.utils.WebServicrUtils;
import com.tywj.buscustomerapp.view.myview.ToastJoe;
import com.umeng.analytics.MobclickAgent;

import org.xmlpull.v1.XmlPullParserException;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import butterknife.BindView;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class ApplyActivity extends BaseActivity {
    @BindView(R.id.head_left) ImageView back;
    @BindView(R.id.head_title) TextView title;
    @BindView(R.id.application_home) TextView home;
    @BindView(R.id.application_work) TextView work;
    @BindView(R.id.application_time) TextView time;
    @BindView(R.id.application_time1) TextView time1;
    @BindView(R.id.cs_submit) TextView submit;
    @BindView(R.id.line1) LinearLayout line1;
    @BindView(R.id.line2) LinearLayout line2;
    @BindView(R.id.line3) LinearLayout line3;
    @BindView(R.id.line4) LinearLayout line4;
    @BindView(R.id.head_img) ImageView head_img;

    private TimePickerView timePickerView;
    private PoiItem startPoi;
    private PoiItem endPoi;
    private double[] address;
    private String cityName;
    private String startLat;
    private String startLon;
    private String endLat;
    private String endLon;


    @Override
    protected int getContentId() {
        return R.layout.activity_apply;
    }

    @Override
    protected void initWidget(Bundle savedInstanceState) {
        super.initWidget(savedInstanceState);
        title.setText(R.string.application_name);
        if (getIntent()!=null){
            home.setText(SPUtils.getStartAndEnd(getApplicationContext())[0]);
            work.setText(SPUtils.getStartAndEnd(getApplicationContext())[1]);
            cityName = "成都市";
            address = getIntent().getDoubleArrayExtra("address");
            if (address!=null){
                startLat = address[0]+"";
                startLon = address[1]+"";
                endLat  = address[2]+"";
                endLon = address[3]+"";
            }

        }
        Glide.with(this).load(R.drawable.car).into(head_img);

    }

    @Override
    protected void initData() {
        super.initData();
        boolean[] type = {false,false,false,true,true,false};
        timePickerView = new TimePickerBuilder(ApplyActivity.this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
                String timeString = sdf.format(date);
                switch (v.getId()){
                    case R.id.line3:
                        time.setText(timeString);
                        break;
                    case R.id.line4:
                        time1.setText(timeString);
                        break;
                }
            }
        }).setType(type)
                .isDialog(true)
                .setSubmitColor(getResources().getColor(R.color.appColor))
                .setCancelColor(getResources().getColor(R.color.gray1)).build();
       Dialog mDialog = timePickerView.getDialog();
        if (mDialog != null) {

            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    Gravity.BOTTOM);

            params.leftMargin = 0;
            params.rightMargin = 0;
            timePickerView.getDialogContainerLayout().setLayoutParams(params);

            Window dialogWindow = mDialog.getWindow();
            if (dialogWindow != null) {
                dialogWindow.getDecorView().setPadding(0, 0, 0, 0);
                WindowManager.LayoutParams lp = dialogWindow.getAttributes();
                lp.width = WindowManager.LayoutParams.MATCH_PARENT;
                lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
                dialogWindow.setAttributes(lp);
                dialogWindow.setWindowAnimations(com.bigkoo.pickerview.R.style.picker_view_slide_anim);//修改动画样式
                dialogWindow.setGravity(Gravity.BOTTOM);//改成Bottom,底部显示
            }
        }
    }

    @Override
    protected void initClick() {
        super.initClick();
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        line1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        line2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        line3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                timePickerView.show(v);
            }
        });
        line4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                timePickerView.show(v);
            }
        });
        line1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(ApplyActivity.this, ChooseLocationActivity.class);
                intent.putExtra("type",2);
                startActivityForResult(intent,3001);
            }
        });

        line2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(ApplyActivity.this, ChooseLocationActivity.class);
                intent.putExtra("type",3);
                startActivityForResult(intent,3002);
            }
        });

        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.i("Taylor","click");
                final String homeaddress = home.getText().toString();
                final String workaddress = work.getText().toString();
                final String starttime = time.getText().toString();
                final String endtime = time1.getText().toString();
                if (homeaddress.equals("") || homeaddress.equals("选择家庭地址")){
                    ToastJoe.getmToastJoe().ToastShow(ApplyActivity.this,null,"请选择家庭住址");
                }else if (workaddress.equals("") || workaddress.equals("选择目的地地址")){
                    ToastJoe.getmToastJoe().ToastShow(ApplyActivity.this,null,"请选择目的地地址");
                }else if (starttime.equals("") || endtime.equals("")||starttime.equals("选择出行时间")||endtime.equals("选择返程时间")){
                    ToastJoe.getmToastJoe().ToastShow(ApplyActivity.this,null,"请选择出行时间和返程时间");
                }else{
                    Observable.create(new ObservableOnSubscribe<String>() {
                        @Override
                        public void subscribe(ObservableEmitter<String> e){
                            try {
                                String msg = WebServicrUtils.getInstance().sendApplyLine(SPUtils.getUserPhone(getApplicationContext())
                                ,homeaddress,workaddress,starttime,endtime,cityName,startLon,
                                        startLat,endLon,endLat);
                                Log.i("Taylor",msg);
                                if (msg.equals("ok")){
                                    e.onNext(msg);
                                }else{
                                    e.onError(null);
                                    Log.i("Taylor3",msg);
                                }
                            } catch (IOException e1) {
                                e1.printStackTrace();
                                Log.i("Taylor","click1");
                                e.onError(null);
                            } catch (XmlPullParserException e1) {
                                e1.printStackTrace();
                                Log.i("Taylor","click2");
                                e.onError(null);
                            }
                        }
                    }).subscribeOn(Schedulers.io())
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe(new Observer<String>() {
                                @Override
                                public void onSubscribe(Disposable d) {

                                }

                                @Override
                                public void onNext(String s) {
                                    ToastJoe.getmToastJoe().ToastShowRight(ApplyActivity.this,null,"上传成功");
                                    finish();
                                }

                                @Override
                                public void onError(Throwable e) {
                                    ToastJoe.getmToastJoe().ToastShow(ApplyActivity.this,null,"上传成功");
                                }

                                @Override
                                public void onComplete() {

                                }
                            });
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode==1001 && data!=null && data.getParcelableExtra("poi")!=null) {
            PoiItem poi = data.getParcelableExtra("poi");
            switch (requestCode) {
                case 3001:
                    home.setText(poi.getTitle());
                    startPoi = poi;
                    cityName = startPoi.getCityName();
                    startLon = startPoi.getLatLonPoint().getLongitude()+"";
                    startLon = startPoi.getLatLonPoint().getLatitude()+"";
                    break;
                case 3002:
                    work.setText(poi.getTitle());
                    endPoi = poi;
                    endLon = endPoi.getLatLonPoint().getLongitude()+"";
                    endLat = endPoi.getLatLonPoint().getLatitude()+"";
                    break;
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("线路申请1");
        MobclickAgent.onResume(this); //统计时长

    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("线路申请1");
        MobclickAgent.onPause(this);
    }
}
